<template>
  <div>
    <JiraModal ref="issueSubmit"></JiraModal>
    <el-container>
      <el-aside width="200px">{{ this.returnText }}</el-aside>
      <el-container>
        <el-header>
          <div v-show="showTask" >
            <el-row :gutter="2">
              <el-col :span="2">
                通过率: {{ recordInfo.passRate + '%' }}
              </el-col>
              <el-col :span="2">
                已测: {{ recordInfo.passCount + '/' + recordInfo.totalCount }}
              </el-col>
              <el-col :span="2">
                通过: {{ recordInfo.successCount + '/' + recordInfo.totalCount }}
              </el-col>
              <el-col :span="2">
                阻塞: {{ recordInfo.blockCount + '/' + recordInfo.totalCount }}
              </el-col>
              <el-col :span="2">
                失败: {{ recordInfo.bugNum + '/' + recordInfo.totalCount }}
              </el-col>
              <el-col :span="3">
                未执行: {{ recordInfo.totalCount - recordInfo.passCount + '/' + recordInfo.totalCount }}
              </el-col>
              <el-col :span="4">
                计划周期: {{ TaskStartTime + ' 至 ' + TaskEndTime }}
              </el-col>
            </el-row>
          </div>
        </el-header>
        <el-main>
          <VueTestcaseMinderEditor
            ref="minderEditor"
            :initJson="initJson"
            :allow-edit-priority="editMode"
            :allow-edit-label="editMode"
            :allow-edit-result="resultMode"
            :allow-edit-node="editMode"
            :showSaveBtn="showSaveBtn"
            @afterMount="afterMount()"
            @saveMinder="updateCase">
          </VueTestcaseMinderEditor>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
// import 'vue-minder-testcase/lib/VueTestcaseMinderEditor.css'
import request from '@/utils/axios'
import { Message } from 'element-ui'
import getQueryString from '@/utils/getCookies';
import {dateFormatYmdHMS, dateFormatYmd} from "@/views/casepage/DateFormat";
import store from '@/store';
import { mapGetters } from 'vuex'
import {getSelectedNodeData} from "@/components/case/casemgmt/minderUtils";
import {warning} from "@/utils/message";
import JiraModal from "@/components/Task/JiraModal";
import TaskModal from "@/components/Task/TaskModal";
const getCookies = getQueryString.getCookie;

export default {
  name: 'CaseMgmt',
  components: {JiraModal},
  data() {
    return {
      initJson: {
        root: {
          data: {
            text: '主题',
            id: '0'
          },
          children: [
            { data: { text: '分支', id: '1', resource: ['自定义标签'] }}
          ]
        }
      },
      baseCaseContent: {},
      resultMode: true,
      recordInfo: '',
      showTask: false,
      TaskStartTime:'',
      TaskEndTime:'',
      returnText: '',
    }
  },
  props: {
    showSaveBtn: {
      type: Boolean,
      default: true
    },
    editMode: {
      type: Boolean,
      default: true
    }
  },
  async created() {
    const taskId = this.$route.params.taskId;
    const addressUrl = this.$route
    if (taskId && taskId !== '0') {
      this.showTask = true
      this.baseCaseContent = await this.getRecordDetailById()
      this.getRecordInfoById()
    } else if (addressUrl.name === '用例详情') {
      this.showTask = false
      this.resultMode = false
      this.baseCaseContent = await this.getCaseDetailByCaseId();
      this.getCaseInfoById()
    }
    // console.log('刚打开界面时的用例数据：', this.baseCaseContent);
    // this.timer = setInterval(() => {
    //   setTimeout(() => {
    //     this.updateCase();
    //   }, 1000)
    // }, 3600000)
  },
  methods: {
    clearBtn: function (){
      const taskId = this.$route.params.taskId;
      return taskId && taskId !== '0'
    },
    handleAutoSave(e) {
      e.preventDefault()
      e.returnValue = ''
      localStorage.setItem(window.location.href, JSON.stringify(this.$refs.minderEditor.getJsonData()))
      const minderData = this.$refs.minderEditor
        ? this.$refs.minderEditor.getJsonData()
        : {}
      if (minderData && Object.keys(minderData).length > 0) {
        this.updateCase()
      }
    },
    updateCase: async function() {
      const caseJson = this.$refs.minderEditor.getJsonData();
      // console.log('当前编辑器中的用例数据', JSON.stringify(caseJson));
      let reason = "";
      if (this.showTask) {
        this.reason = " save result";
      } else {
        this.reason = " save testcase";
      }
      // console.log('保存前用例数据：',this.baseCaseContent);
      let recordId = this.$route.params.taskId ? this.$route.params.taskId: ''
      const param = {
        id: this.$route.params.caseId,
        title: '更新内容，实际不会保存title',
        recordId,
        modifier: getCookies('username'),
        caseContent: JSON.stringify(caseJson),
        baseCaseContent: this.baseCaseContent,
        saveReason: dateFormatYmdHMS(Date()) + this.reason
      };
      let url ='/case/update'
      request(url, {method: 'POST', body: param }).then(async res => {
        if (res.code === 200) {
          if (this.showTask) {
            this.baseCaseContent = await this.getRecordDetailById()
            this.getRecordInfoById()
          } else {
            this.baseCaseContent = await this.getCaseDetailByCaseId()
          }
          // console.log('保存后用例数据：',this.baseCaseContent);
          Message.success('保存內容成功');
        } else {
          Message.error(res.msg);
        }
      })
    },
    clearRecord :function () {
      const params = {
        id: this.$route.params.taskId,
        modifier: getCookies('username'),
      };
      const taskId  = this.$route.params.taskId;
      let url = '/record/clear';
      request(url, {method: 'POST', body: params}).then(res => {
        if(res.code === 200) {
          Message.success('clear record success');
          this.initJson = JSON.parse(res.data.caseContent);
          if (taskId && taskId !== '0') {
            this.getRecordInfoById();
          }
        } else {
          Message.error(res.msg);
        }
      });
    },
    getRequirementsById: function(requirementIds) {
      request('/business-lines/requirements', {
        method: 'GET',
        params: { requirementIds: requirementIds }
      }).then(res => {
        this.setState({ requirementObj: res, loading: false })
      })
    },
    getCaseInfoById: function() {
      const url = '/case/getCaseInfo'
      const _this = this;
      request(url, {
        method: 'GET',
        params: { id: this.$route.params.caseId }
      }).then(res => {
        if (res.code === 200) {
          _this.caseInfo = res.data
          document.title = res.data.title + ' - ' + this.$route.meta.title
          // 左边表达式为true,就会执行右边表达式; 根据requirementsId 获取需求名称（todo）
          // _this.caseInfo.requirementId && _this.getRequirementsById(this.caseInfo.requirementId)
        } else {
          _this.$router.push('/case/list/1')
          Message.error(res.msg)
        }
      })
    },
    getCaseDetailByCaseId: function() {
      return new Promise((resolve,reject) => {
        const url = '/case/detail'
        const caseId = this.$route.params.caseId
        request(url, {
          method: 'GET',
          params: { caseId: caseId }
        }).then (res => {
          if (res.code === 200) {
            this.initJson = JSON.parse(res.data.caseContent);
            resolve(res.data.caseContent);
          } else {
            Message.error(res.msg)
            reject(res.msg)
          }
        },err => {
          reject(err)
        })
      })
    },
    getRecordInfoById: function() {
      const url = '/record/getRecordInfo'
      request(url, {
        method: 'GET',
        params: { id: this.$route.params.taskId }
      }).then(res => {
        if (res.code === 200) {
          this.recordInfo = res.data
          document.title = res.data.title + ' - ' + this.$route.meta.title
        } else {
          Message.error(res.msg)
        }
      })
    },
    getRecordDetailById: function() {
      return new Promise((resolve,reject) => {
        const url = '/record/getRecordDetail'
        request(url, {
          method: 'GET',
          params: { recordId: this.$route.params.taskId }
        }).then(res => {
          if (res.code === 200) {
            const recordDetail = res.data
            this.initJson = JSON.parse(res.data.caseContent)
            this.TaskStartTime = dateFormatYmd(recordDetail.expectStartTime)
            this.TaskEndTime = dateFormatYmd(recordDetail.expectEndTime)
            resolve(res.data.caseContent);
          } else {
            Message.error(res.msg)
            reject(res.msg)
          }
        },err => {
          reject(err)
        })
      })
    },
    afterMount() {
      let self = this
      let returnText = ''

      minder.on('contentchange', function (env) {
        console.log('contentchange');
        // console.log(env);
        let selectNodes = env.minder.getSelectedNode();
        console.log(selectNodes.getText());
        console.log("=====");

      });

      minder.on('beforeExecCommand', function (env) {
        console.log('beforeExecCommand');
        console.log(env);
      });

      minder.on && minder.on('interactchange', function(event) {
        self.selectedNodeCount = event.minder.getSelectedNodes().length
        if (self.selectedNodeCount === 1) {
          self.selectedNodeText = event.minder.getSelectedNodes()[0].data.text
        } else {
          self.selectedNodeText = ''
        }
        returnText = "当前选中的节点数：" + self.selectedNodeCount
        if (self.selectedNodeText) {
          returnText += " 当前选中节点的文字内容：" + self.selectedNodeText
        }
        console.log(returnText)
        self.returnText = returnText;
      });

      if (this.showTask) {
        this.addHotBox(this);
      }
    },
    addHotBox(vueObj) {
      let hotbox = window.minder.hotbox;
      let main = hotbox.state('main');
      main.button({
        position: 'ring',
        label: '提交缺陷',
        key: 'N',
        action: function () {
          // this.$refs.issueRelate.open();
          console.log('打开提交缺陷对话框')
          vueObj.$refs.issueSubmit.showDialog()
        },
        enable: function () {
          return true;
        },
        beforeShow: function () {
        }
      })
    }
  }
}

</script>

<style scoped>

.el-header {
  background-color: #B3C0D1;
  color: #333;
  text-align: center;
  line-height: 60px;
}

.el-main {
  background-color: #E9EEF3;
  color: #333;
  text-align: center;
  line-height: 160px;
}

.el-aside {
  background-color: #D3DCE6;
  color: #333;
  text-align: center;
  line-height: 200px;
}

body > .el-container {
  margin-bottom: 40px;
}

.el-button:active {
  background: #126c9e !important;
  font-weight: bold;
}
/*按钮悬浮*/
.el-button:hover {
  background: #126c9e !important;
  color: white !important;
  font-weight: bold;
  border-color: #01a8f9 !important;
}
/*按钮点击*/
.el-button:focus {
  background: #126c9e !important;
  color: white !important;
  font-weight: bold;

  border-color: #01a8f9 !important;
}
</style>
